package com.hnepri.fang.ftx2.fetch.residential;

import com.hnepri.fang.ftx2.fetch.APageBridge;
import com.hnepri.fang.ftx2.fetch.HttpUtil;
import com.hnepri.fang.ftx2.fetch.IPage;

import java.io.File;
import java.io.IOException;

/**
 * 小区简介初始化类
 */
public class ResidentialFetch {
    private String city;
    private int pageSize;
    private String storePath;
    private String urlPattern = "http://${city}.esf.fang.com/housing/__0_0_0_0_${page}_0_0_0/";
    public ResidentialFetch(String city, String storePath) {
        this.city = city;
        this.storePath = storePath;
        this.initPageSize();
    }
    private void initPageSize() {
        //小区简介列表页面url模式
        String url = urlPattern.replace("${city}", city).replace("${page}", "1");
        try {
            String html = HttpUtil.getPageHtml(url);
            this.pageSize = new ResidentialPageParser().getPageSize(html);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 开启取数据
     * @param threadLen  线程数
     */
    public void go(int threadLen) {
        String path = storePath + "/" + city + "/jianjie";
        File file = new File(path);
        File pdir = file.getParentFile();
        if (!pdir.exists()) {
            pdir.mkdir();
        }
        if (!file.exists()) {
            file.mkdir();
        }

        int groupStep = pageSize / threadLen;//每个线程查询多少页面
        int extralPage = pageSize % threadLen;

        int startPage = 1;

        //核心业务类，处理网页,虽然是多线程，但没有共享变量，所以不用担心
        APageBridge residentialPageConcrete = new ResidentialPageBridgeConcrete();
        IPage page = new ResidentialPageImpl();
        residentialPageConcrete.setPage(page);


        for(int i = 0; i < threadLen; i++) {

            ResidentialThread residentialThread = new ResidentialThread();

            residentialThread.setUrlPattern(urlPattern);
            residentialThread.setCity(city);
            residentialThread.setPath(path);
            residentialThread.setStartPage(startPage);
            residentialThread.setEndPage(startPage + groupStep - 1);
            residentialThread.setResidentialPageConcrete(residentialPageConcrete);

            residentialThread.start();

            startPage += groupStep;
        }
        if (extralPage > 0) {
            ResidentialThread residentialThread = new ResidentialThread();

            residentialThread.setUrlPattern(urlPattern);
            residentialThread.setCity(city);
            residentialThread.setPath(path);
            residentialThread.setStartPage(startPage);
            residentialThread.setEndPage(startPage + groupStep - 1);
            residentialThread.setResidentialPageConcrete(residentialPageConcrete);

            residentialThread.start();
        }
    }

    public static void main(String[] args) {
        String path = "E:/小区";
        ResidentialFetch residentialFetch = new ResidentialFetch("jiyuan", path);
        residentialFetch.go(4);
    }
}
